package com.xg.te.strategy;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.jarveis.frame.io.HttpUtil;
import com.jarveis.frame.io.HttpUtil.HttpMethod;
import com.jarveis.frame.lang.StringUtil;
import com.jarveis.frame.util.JsonUtil;
import com.jarveis.frame.util.Pager;
import com.jarveis.frame.util.Result;
import com.xg.te.core.WebsiteStore;
import com.xg.te.core.bean.WebsiteBean;

/**
 * @desc 消息队列策略
 * @author liuguojun
 * @date 2016-09-28
 */
public class MessageQueueStrategy extends Strategy {

	public void execute(JSONObject jsonObj) {
		try {
			String dataLink = jsonObj.getString("data");
			String websitetCode = jsonObj.getString("websiteCode");
			
			List values = getQueueValues(websitetCode, dataLink);
			if (values == null) {
				return ;
			}
			
			for (Iterator vit = values.iterator(); vit.hasNext();){
				Map valueMap = (Map)vit.next();
				Map<String, Object> args = new HashMap<String, Object>(1);
				args.put("queueValue", (String)valueMap.get("value"));
				
				for (Iterator<String> it = pages.iterator(); it.hasNext();) {
					String pageCode = it.next();

					String[] arr = pageCode.split("_");
					if (arr.length != 2) {
						continue;
					}
					staticHtml(arr[0], arr[1], args);
				}
			}
			
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}
	}

	/**
	 * 
	 * @param websitetCode
	 * @param dataLink
	 * @param queueKey
	 * @return
	 * @throws Exception
	 */
	private List getQueueValues(String websitetCode, String dataLink) throws Exception {
		if (StringUtil.isEmpty(dataLink)) {
			throw new Exception("parameter data is empty");
		}

		if (!StringUtil.isEmpty(websitetCode)) {
			WebsiteBean website = WebsiteStore.get(websitetCode);
			String webService = website.getConstantValue("webService");
			dataLink = webService + dataLink;
		}

		String resultStr = connect(dataLink);
		Result result = (Result) JsonUtil.parse(resultStr);
		if (result.isSuccess()) {
			Object data = result.getData();
			if (data instanceof Pager) {
				return ((Pager) data).getData();
			}
		}

		return null;
	}

	/**
	 * 获取根节点
	 * 
	 * @param file
	 * @return
	 */
	private String connect(String uri) {
		String result = "";

		HttpUtil http = new HttpUtil(uri, HttpMethod.GET);
		if (http.doRequest()) {
			result = new String(http.getRespData());
		}

		return result;
	}

}
